//并行 Promise.all
function parallel(...args) {
    Promise.all(args).then(res => {
        console.log(res)
    })
}

const p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(1)
    }, 1000)
})

const p2 = new Promise((resolve, reject) => {
    resolve(2)
})

const p3 = Promise.resolve(3)

// parallel(p2, p1, p3)

//串行 因为promise创建就会执行，所以task只能存函数包住promise
function serial(task) {
    const result = []
    const len = task.length
    let index = 0
    return new Promise((resolve, reject) => {
        function resolvePromise(index) {
            if(index >= len) {
                resolve(result)
            } else {
                task[index]().then(res => {  
                    result.push(res)
                    resolvePromise(++index)
                }, () => {
                    reject('error')
                })
            }
        }
        resolvePromise(index)
    })
}

const task = [
    () => new Promise((resolve, reject) => {
        // console.log('this is first')
        resolve(2)
    }),
    () => new Promise((resolve, reject) => {
        reject(1)
    }),
    () => new Promise((resolve, reject) => {
        resolve(3)
    }),
]

serial(task).then(res => {
    console.log(res)
}, err => {
    console.log(err)
})

